<template>
  <TopNav :title="metaTitle" />
  <Listing
    v-if="items && items.results.length"
    :title="metaTitle"
    :items="items"
    :loading="loading"
    @loadMore="loadMore"
  />
</template>
<script setup>
import Listing from "@/components/Listing.vue";
import TopNav from "@/components/TopNav.vue";
import { computed, ref } from "vue";
import { useRoute } from "vue-router";
import { getMediaByGenre, getGenreList } from "@/api";

const genre = ref(null);
const items = ref(null);
const loading = ref(false);

const route = useRoute();

const metaTitle = computed(() => {
  if (genre.value) {
    return `TV Genre: ${genre.value.name}`;
  } else {
    return `TV Genre`;
  }
});

Promise.all([getMediaByGenre("tv", route.params.id), getGenreList("tv")])
  .then(([itemsRes, genresRes]) => {
    const genres = genresRes.genres;
    const genreResult = genres.find(
      (genre) => genre.id === parseInt(route.params.id)
    );
    if (genreResult) {
      genre.value = genreResult;
      items.value = itemsRes;
    } else {
      console.error("Page not found");
    }
  })
  .catch((error) => {
    console.error(error);
  });

const loadMore = () => {
  loading.value = true;
  getMediaByGenre("tv", route.params.id, items.value.page + 1)
    .then((res) => {
      items.value.results = items.value.results.concat(res.results);
      items.value.page = res.page;
    })
    .finally(() => {
      loading.value = false;
    });
};
</script>
